package com.cxm.helper.controller.admin;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.cxm.helper.exception.BusinessException;
import com.cxm.helper.pojo.dto.CategorySaveDTO;
import com.cxm.helper.service.CategoryService;
import com.cxm.helper.service.impl.AliyunOssService;
import com.cxm.helper.util.ResponseEntity;
import com.cxm.helper.util.constant.AliyunOssConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author: chenximeng
 * @date: 2022/11/23 14:12
 */
@Slf4j
@RestController
@RequestMapping("/admin/category")
@SaCheckRole("admin")
public class CategoryAdminController {

    @Autowired
    CategoryService categoryService;
    @Autowired
    AliyunOssService aliyunOssService;

    @PostMapping("/save")
    public ResponseEntity save(@RequestBody CategorySaveDTO categorySaveDTO) {
        categoryService.saveOrUpdate(categorySaveDTO);
        return ResponseEntity.ok();
    }

    @PostMapping("/uploadAvatar")
    public ResponseEntity uploadCategoryAvatar(MultipartFile file){
        String url;
        try{
            url = aliyunOssService.uploadFileAvatar(file, AliyunOssConstant.CATEGORY_AVATAR_PATH);
        }catch (Exception e) {
            log.error("文件上传报错",e);
            throw new BusinessException("上传文件失败");
        }
        ResponseEntity<String> ok = ResponseEntity.ok();
        return ok.setData(url);
    }

    @DeleteMapping("/delete/{id}")
    public ResponseEntity delete(@PathVariable Long id) {
        categoryService.removeById(id);
        return ResponseEntity.ok();
    }
}
